package com.css.openapi.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.constant.Result;
import com.css.common.core.constant.ReturnCode;
import com.css.common.core.constant.SystemCodeEnum;
import com.css.common.core.enums.YwlxEnum;
import com.css.common.core.exception.ServiceException;
import com.css.common.core.utils.BaseUtil;
import com.css.common.core.utils.GyUtils;
import com.css.openapi.BO.ShxxdjKzdjxxVo;
import com.css.openapi.BO.ShxxdjReq;
import com.css.openapi.entity.QyYwlx;
import com.css.openapi.entity.QyxxKz;
import com.css.openapi.entity.RecyclingEnterpriseInfo;
import com.css.openapi.entity.ZfjkpYhFjxxDO;
import com.css.openapi.feign.ZfjkpPtCommonClient;
import com.css.openapi.mapper.QyxxKzMapper;
import com.css.openapi.service.IQyYwlxService;
import com.css.openapi.service.IQyxxKzService;
import com.css.openapi.service.RecyEnteService;
import com.css.openapi.service.ZfjkpYhFjxxService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 企业信息扩展表 服务实现类
 * </p>
 *
 * @author qinxb
 * @since 2025-01-20 02:07:37
 */
@Service
@Slf4j
public class QyxxKzServiceImpl extends ServiceImpl<QyxxKzMapper, QyxxKz> implements IQyxxKzService {
    @Resource
    private IQyYwlxService ywlxService;
    @Resource
    private RecyEnteService recyEnteService;
    @Resource
    private ZfjkpYhFjxxService yhFjxxService;
    @Resource
    private ZfjkpPtCommonClient zfjkpPtCommonClient;

    @Override
    @Transactional
    public Result shxxdj(ShxxdjReq shxxdjReq) {
        log.info("商户信息登记参数：{}",JSON.toJSONString(shxxdjReq));
        //校验
        List<QyYwlx> qyYwlxs = ywlxService.lambdaQuery()
                .eq(QyYwlx::getShbdbh, shxxdjReq.getShbdbh())
                .eq(QyYwlx::getScbj, "0").list();
        if (CollectionUtils.isEmpty(qyYwlxs)) {
            throw new ServiceException("未查询到商户绑定编号信息，请先进行商户绑定申请");
        } else {
            QyYwlx qyYwlxxx=null;
            for (QyYwlx qyYwlx : qyYwlxs) {
                if(Objects.equals(qyYwlx.getYwlxDm(),shxxdjReq.getYwlx())){
                    qyYwlxxx=qyYwlx;
                    break;
                }
            }
            if(Objects.isNull(qyYwlxxx))throw new ServiceException("商户绑定编号没有开通此业务类型，请先进行商户绑定申请");
            if (Objects.equals(shxxdjReq.getYwlx(), qyYwlxxx.getYwlxDm()) && Objects.equals("00", qyYwlxxx.getBdzt())) {
                throw new ServiceException("商户绑定编号已绑定业务类型：" + shxxdjReq.getYwlx() + "，无需再次登记");
            }
        }
        //调用支付即开票平台
        ReturnCode re=zfjkpPtCommonClient.shxxDj(shxxdjReq);
        if(!Objects.equals(re.getCode(),"0"))throw new ServiceException(re.getMsg());
        //保存数据
        QyYwlx qyYwlx = qyYwlxs.get(0);
        RecyclingEnterpriseInfo info = recyEnteService.lambdaQuery().eq(RecyclingEnterpriseInfo::getTyshxydm, qyYwlx.getShsh())
                .eq(RecyclingEnterpriseInfo::getScbj, "0").in(RecyclingEnterpriseInfo::getSqzt, Lists.newArrayList("0", "1"))
                .orderByDesc(RecyclingEnterpriseInfo::getCjsj).last(" limit 1").one();
        boolean isYyjcxx = false;
        if (!Objects.isNull(info)) {
            checkDjkzxx(shxxdjReq, shxxdjReq.getYwlx());
            //有数据，基础附件信息沿用
            shxxdjReq.setYyzz(info.getYyzz());//沿用附件uuid
            shxxdjReq.setKhxkz(info.getKhxkz());
            shxxdjReq.setFrsfzzm(info.getFrsfzjzm());
            shxxdjReq.setFrsfzfm(info.getFrsfzjfm());
            shxxdjReq.setQymtz(info.getQymtzp());
            isYyjcxx = true;
        }
        log.info("保存商户信息");
        saveQyxx(isYyjcxx, shxxdjReq, qyYwlx);
        return Result.ok();
    }

    private void saveQyxx(boolean isYyjcxx, ShxxdjReq shxxdjReq, QyYwlx qyYwlx) {
        //保存回收企业信息
        RecyclingEnterpriseInfo recyEnteInfo = new RecyclingEnterpriseInfo();
        final String qyid = IdUtil.fastSimpleUUID();
        recyEnteInfo.setQyid(qyid);
        recyEnteInfo.setSqzt("0");
        recyEnteInfo.setScbj("0");
        recyEnteInfo.setTyshxydm(qyYwlx.getShsh());
        recyEnteInfo.setQymc(qyYwlx.getShmc());
        recyEnteInfo.setQydh(shxxdjReq.getShdh());
        recyEnteInfo.setQydz(shxxdjReq.getShdz());
        recyEnteInfo.setCjr(qyYwlx.getLxrsjh());
        recyEnteInfo.setCjsj(LocalDateTime.now());
        recyEnteInfo.setDgyhzh(shxxdjReq.getDgyhzh());
        recyEnteInfo.setDgyhhh(shxxdjReq.getDgyhhh());
        recyEnteInfo.setSqrxm(qyYwlx.getLxrmc());
        recyEnteInfo.setSqrsfzh(qyYwlx.getLxrsfzjhm());
        recyEnteInfo.setSqrsjh(qyYwlx.getLxrsjh());
        //新增字段
        recyEnteInfo.setShbdbh(qyYwlx.getShbdbh());
        recyEnteInfo.setYwlxDm(shxxdjReq.getYwlx());
        recyEnteInfo.setFrxm(shxxdjReq.getFrxm());
        recyEnteInfo.setFrsfzhm(shxxdjReq.getFrsfzhm());
        recyEnteInfo.setJrzx(shxxdjReq.getJrzx());
        //组装附件信息
        List<ZfjkpYhFjxxDO> fjxxDOList = new ArrayList<>();
        //营业执照
        String yyzzUuid = isYyjcxx ? shxxdjReq.getYyzz() : IdUtil.fastSimpleUUID();
        //开户许可证
        String khxkUuid = isYyjcxx ? shxxdjReq.getKhxkz() : IdUtil.fastSimpleUUID();
        //法人身份证正面
        String sfzzmUuid = isYyjcxx ? shxxdjReq.getFrsfzzm() : IdUtil.fastSimpleUUID();
        //法人身份证正面
        String sfzfmUuid = isYyjcxx ? shxxdjReq.getFrsfzfm() : IdUtil.fastSimpleUUID();
        //法人身份证正面
        String qymtUuid = isYyjcxx ? shxxdjReq.getQymtz() : IdUtil.fastSimpleUUID();
        recyEnteInfo.setYyzz(yyzzUuid);
        recyEnteInfo.setKhxkz(khxkUuid);
        recyEnteInfo.setFrsfzjzm(sfzzmUuid);
        recyEnteInfo.setFrsfzjfm(sfzfmUuid);
        recyEnteInfo.setQymtzp(qymtUuid);
        if (!isYyjcxx) {
            log.info("企业没有审核基础信息，保存新附件");
            addFjxx(fjxxDOList, yyzzUuid, "营业执照", shxxdjReq.getYyzz());
            addFjxx(fjxxDOList, khxkUuid, "开户许可证", shxxdjReq.getKhxkz());
            addFjxx(fjxxDOList, sfzzmUuid, "法人身份证正面", shxxdjReq.getFrsfzzm());
            addFjxx(fjxxDOList, sfzfmUuid, "法人身份证反面", shxxdjReq.getFrsfzfm());
            addFjxx(fjxxDOList, qymtUuid, "企业门头照片", shxxdjReq.getQymtz());
        } else {
            log.info("企业已有审核基础信息，保存沿用附件：{}", JSON.toJSONString(recyEnteInfo));
        }
        log.info("保存商户信息,赋值企业信息");
        //附件扩展字段
        ShxxdjKzdjxxVo shxxdjKzdjxxVo = shxxdjReq.getKzdjxx();
        QyxxKz kz = new QyxxKz();
        kz.setUuid(IdUtil.fastSimpleUUID());
        kz.setQyid(qyid);
        kz.setScbj("0");
        kz.setCjsj(LocalDateTime.now());
        if (!Objects.isNull(shxxdjKzdjxxVo)) {
            //报废机动车回收拆解企业资质认定书
            String zzrdsUuid = IdUtil.fastSimpleUUID();
            if(!BaseUtil.isNull(shxxdjKzdjxxVo.getBfjdchscjqyzzrds())){
                kz.setBfjdchscjqyzzrds(zzrdsUuid);
            }
            addFjxx(fjxxDOList, zzrdsUuid, "报废机动车回收拆解企业资质认定书", shxxdjKzdjxxVo.getBfjdchscjqyzzrds());
            //再生资源回收经营者备案登记证
            String zbzdjzUuid = IdUtil.fastSimpleUUID();
            if(!BaseUtil.isNull(shxxdjKzdjxxVo.getZszyhsjyzbadjz())){
                kz.setZszyhsjyzbzdjz(zbzdjzUuid);
            }
            addFjxx(fjxxDOList, zbzdjzUuid, "再生资源回收经营者备案登记证", shxxdjKzdjxxVo.getZszyhsjyzbadjz());
            //危险废物经营许可证
            String jyxkzUuid = IdUtil.fastSimpleUUID();
            if(!BaseUtil.isNull(shxxdjKzdjxxVo.getWxfwjyxkz())){
                kz.setWxfwjyxkz(qymtUuid);
            }
            addFjxx(fjxxDOList, jyxkzUuid, "危险废物经营许可证", shxxdjKzdjxxVo.getWxfwjyxkz());
        }
        if (!CollectionUtils.isEmpty(fjxxDOList)) {
            log.info("附件条数：" + fjxxDOList.size());
            yhFjxxService.saveBatch(fjxxDOList);
        }
        log.info("保存商户信息,保存附件信息：{}",fjxxDOList.size());
        boolean flag = this.recyEnteService.save(recyEnteInfo);
        if (!flag) throw new ServiceException(SystemCodeEnum.SYSTEM_ERR.getCode(), "存储企业信息异常！");
        if (YwlxEnum.YWLX_ZSZYHS.getDm().equals(shxxdjReq.getYwlx())) {
            boolean is=this.save(kz);
            if (!is) throw new ServiceException(SystemCodeEnum.SYSTEM_ERR.getCode(), "存储扩展信息异常！");
        }
    }

    private void addFjxx(List<ZfjkpYhFjxxDO> fjxxDOList, String uuid, String fjmc, String fjBase64) {
        if(BaseUtil.isNull(fjBase64)){
            log.info("添加附件"+fjmc+",附件为空");return;
        }
        ZfjkpYhFjxxDO fjxxDO = new ZfjkpYhFjxxDO();
        fjxxDO.setUuid(uuid);
        fjxxDO.setFjmc(fjmc);
        fjxxDO.setTp64(fjBase64);
        fjxxDO.setCjsj(LocalDateTime.now());
        fjxxDO.setScbj("0");
        fjxxDO.setCjr(Long.valueOf("0"));
        fjxxDOList.add(fjxxDO);
    }

    private void checkDjkzxx(ShxxdjReq shxxdjReq, String ywlx) {
        ShxxdjKzdjxxVo kzdjxxVo = shxxdjReq.getKzdjxx();
        if (YwlxEnum.YWLX_ZSZYHS.getDm().equals(ywlx)) {
            if (GyUtils.isNull(kzdjxxVo)) {
                throw new ServiceException("扩展登记信息不能为空");
            }
            String yxkz = kzdjxxVo.getWxfwjyxkz();
            String qyzzrds = kzdjxxVo.getBfjdchscjqyzzrds();
            String jyzbzdjz = kzdjxxVo.getZszyhsjyzbadjz();
            if (BaseUtil.isNull(yxkz)&&BaseUtil.isNull(qyzzrds)&&BaseUtil.isNull(jyzbzdjz)) {
                throw new ServiceException("危险废物经营许可证，报废机动车回收拆解企业资质认定书，再生资源回收经营者备案登记证不能同时为空");
            }
        }
    }

}
